<template>
    <div>
        <h2 class="login-title" v-if="currentStep == 1 || currentStep == 2">欢迎使用GpuMall</h2>
        <div class="step-1" v-if="currentStep == 1">
            <div class="login-type">
                <div :class="{ 'activeType': loginType == 1 }">忘记密码</div>
            </div>
            <a-form loading :model="state.formState" name="normal_login" class="login-form" @finish="nextStep">
                <a-form-item name="phone" :rules="[{ required: true, message: '请输入用户名!' }]">
                    <a-input v-model:value="state.formState.phone" allowClear autocomplete="off" size="large"
                        placeholder="请输入手机号">
                        <template #prefix>
                            <svg-icon name="icon_account_a" style="width: 12px;height: 12px;" />
                        </template>
                    </a-input>
                </a-form-item>

                <a-form-item name="code" :rules="[{ required: true, message: '请输入验证码!' }]">
                    <div class="form-item-code">
                        <a-input v-model:value="state.formState.code" allowClear autocomplete="off" size="large"
                            placeholder="验证码">
                            <template #prefix>
                                <svg-icon name="icon_verify" style="width: 12px;height: 12px;" />
                            </template>
                        </a-input>
                        <a-button type="link" :disabled="count != 0" class="get-code-btn" @click.prevent="sendCode()">{{
                            count >
                            0 ? count : '获取验证码' }} </a-button>
                    </div>
                </a-form-item>

                <!-- geetest验证 -->
                <div id="captcha" style="height: 0;">
                    <GeetestCaptcha :captcha-config="state.captchaConfig" />
                </div>
                <a-form-item>
                    <a-button type="primary" style="width: 100%" html-type="submit" size="large" class="login-form-button">
                        下一步
                    </a-button>
                </a-form-item>

                <div class="login-opts">
                    <div><span class="opt" @click="goLogin">返回</span></div>
                </div>
            </a-form>
        </div>

        <div class="step-2" v-if="currentStep == 2">
            <div class="login-type">
                <div :class="{ 'activeType': loginType == 1 }">设置新密码</div>
            </div>
            <a-form loading :model="state.formPwd" class="login-form" @finish="onFinish">
                <a-form-item name="newPassword" :rules="[{ required: true, message: '请输入密码!' }]">
                    <a-input-password v-model:value="state.formPwd.newPassword" autocomplete="off" size="large"
                        placeholder="请输入6-18位包含大小写字母和数字的密码">
                        <template #prefix>
                            <svg-icon name="icon_lock" style="width: 12px;height: 12px;" />
                        </template>
                    </a-input-password>
                </a-form-item>

                <a-form-item name="confirmPassword" :rules="[{ required: true, validator: validPwd, trigger: 'blur', }]">
                    <a-input-password v-model:value="state.formPwd.confirmPassword" autocomplete="off" placeholder="请确认密码"
                        size="large">
                        <template #prefix>
                            <svg-icon name="icon_lock" style="width: 12px;height: 12px;" />
                        </template>
                    </a-input-password>
                </a-form-item>

                <a-form-item>
                    <a-button type="primary" style="width: 100%" html-type="submit" size="large" class="login-form-button">
                        下一步
                    </a-button>
                </a-form-item>

                <div class="login-opts">
                    <div><span class="opt" @click="goLogin">返回登录</span></div>
                </div>
            </a-form>
        </div>

        <div class="step-3" v-if="currentStep == 3">
            <svg-icon name="icon_findPwd_success" style="width: 36px;height: 36px;margin-bottom: 16px;" />
            <div class="success-txt">恭喜，密码找回成功！</div>
            <a-button type="link" class="go-login" @click="goLogin">返回登录</a-button>

        </div>
    </div>
</template>

<script setup>
import { reactive, ref, computed, defineEmits, onMounted } from 'vue'
import { useCountDown } from "@/hooks/sys/useCountDown.js";
import GeetestCaptcha from "./GeetestCaptcha.vue";
import { XsyMessage } from '@/libs/util.toast'
import { isvalidPhone } from '@/libs/util.valid.js'
import { authGetCode } from 'api/modules/api.auth'
import { findPwdApi } from 'api/modules/api.account'

const emit = defineEmits(['goRegister', 'goLogin']);

const { count, countDown } = useCountDown();

const validPwd = async (_rule, value) => {
    if (!value) {
        return Promise.reject('请输入密码');
    } else if (value !== state.formPwd.newPassword) {
        return Promise.reject('两次输入的密码不一致');
    } else {
        return Promise.resolve();
    }
};

const currentStep = ref(1)

const state = reactive({
    formState: {},
    captchaConfig: {
        config: {
            captchaId: "e0ff0f201c666d314840dfd88a2316f8",
            language: "zho",
            product: "bind",
        },
        handler: captchaHandler,
    },
    formPwd: {}
})

const loginType = ref(1)

const nextStep = values => {
    currentStep.value = 2
}

// 点击发送验证码
function sendCode() {
    if (isvalidPhone(state.formState.phone)) {
        if (window.captchaObj) {
            window.captchaObj.showCaptcha();
        } else {
            alert("请等待验证初始化完成");
            return false;
        }
    } else {
        XsyMessage.warning('请输入正确手机号');
    }
}

// 调用发送验证码接口
const GeetestResult = ref()
const getCode = () => {
    const params = {
        scene: 'retrieve-pwd',
        account: state.formState.phone,
        type: 'phone',
        ...GeetestResult.value
    }

    authGetCode(params).then(res => {
        (res.code == 0) && XsyMessage.success('发送成功')
    })
};

function captchaHandler(captchaObj) {
    window.captchaObj = captchaObj;
    captchaObj
        .appendTo("#captcha")
        .onReady(function () {
           
        })
        .onNextReady(function () {
            
        })
        .onBoxShow(function () {
           
        })
        .onError(function (e) {
          
        })
        .onSuccess(function () {
            if (state.captchaConfig.config.product === "bind") {
                validate();
            }
        });
}


function validate() {
    var result = window.captchaObj.getValidate();
	GeetestResult.value = result;
	if (!result) {
		alert("请先完成验证！");
		return;
	}

	countDown(60, getCode)
}

function onFinish() {
    const params = {
        phone: state.formState.phone,
        newPassword: state.formPwd.newPassword || undefined,
        code: state.formState.code || undefined,
    }

    findPwdApi(params).then(res => {
        currentStep.value = 3
    }).catch(() => {

    })
}

const goLogin = () => {
    emit('goLogin')
}

onMounted(() => {
    let html = document.documentElement;
    html.style.fontSize = 100 * (html.clientWidth / 1440) + "px";
    // 监听 window 的 resize 事件．在浏览器窗口变化时再设置下区域高度．
    window.onresize = () => {
        let html = document.documentElement;
        html.style.fontSize = 100 * (html.clientWidth / 1440) + "px";
    };
})

</script>

<style lang="scss" scoped>
.login-title {
    margin-bottom: 0.64rem;
    color: #222;
    font-family: PingFang SC;
    font-size: 0.32rem;
    font-style: normal;
    font-weight: 600;
    line-height: normal;
}

.login-type {
    display: flex;
    margin-bottom: 0.24rem;

    &>div {
        color: #223354;
        font-family: PingFang SC;
        font-size: 0.16rem;
        font-style: normal;
        font-weight: 500;
        line-height: normal;
        margin-right: 0.24rem;
        cursor: pointer;
    }

    .activeType {
        color: #07F;
    }

    .activeType::after {
        height: 2px;
        content: '';
        background: #07F;
        display: block;
        margin-top: 4px;
    }
}

.login-form {
    overflow: hidden;

    .login-opts {
        display: flex;
        justify-content: space-between;
        color: #333;
        font-family: PingFang SC;
        font-size: 0.12rem;
        font-style: normal;
        font-weight: 500;
        line-height: normal;

        .opt {
            color: #07F;
        }
    }

    .ant-input-affix-wrapper {
        border-radius: 8px;
    }

    .login-code {
        cursor: pointer;
    }
}

.form-item-code {
    position: relative;
    border-radius: 6px;

    .get-code-btn {
        position: absolute;
        right: 0;
        height: 100%;
        border-radius: 0px 4px 4px 0px;
        background: #F2F8FF;
        z-index: 100;
        box-sizing: border-box;
        border: 1px solid #d9d9d9;
        border-left: none;
    }
}

.success-txt {
    color: #223354;
    font-size: 16px;
    font-style: normal;
    font-weight: 500;
    line-height: normal;
    margin-bottom: 16px;
}

.go-login {
    text-decoration: underline
}

.step-3 {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-width: 400px;
    min-height: 400px;
}
</style>
